<template>
  <t-button block theme="warning" @click="handleOpenDialog('create', { orderId: props.orderId })"> 引入方案 </t-button>
  <!-- 自定义对话框 -->
  <custom-dialog
    ref="customDialogRef"
    v-slot="{ formData, readonly }"
    :api-map="{ create: copyProgramme }"
    header="引入方案"
    @request-success="handleDialogRequestSuccess"
  >
    <t-alert message="引入方案后会覆盖原本的项目数据，请谨慎操作！" theme="warning" style="margin-bottom: 20px" />
    <t-form-item label="方案名称" name="programmeId" :rules="[{ required: true, message: '请选择方案名称' }]">
      <t-select
        v-model:value="formData.programmeId"
        :options="programmeList"
        :keys="{ value: 'id', label: 'name' }"
        placeholder="请选择方案名称"
        clearable
        filterable
        :readonly="readonly"
        @clear="formData.programmeId = null"
      />
    </t-form-item>
  </custom-dialog>
</template>

<script setup lang="ts">
import { ref, useTemplateRef } from 'vue';

import { copyProgramme } from '@/api/budget/budget-components';
import { programmeCRUD } from '@/api/budget/programme';
import CustomDialog from '@/components/custom/dialog/index.vue';

// props
const props = defineProps({
  // 订单id
  orderId: {
    type: Number,
    required: true,
  },
  // 公司id
  companyId: {
    type: Number,
    required: true,
  },
});
// emits
const emits = defineEmits(['requestSuccess']);
// 方案列表
const programmeList = ref([]);
// 处理获取方案列表
const handleGetProgrammeList = () => {
  const params = {
    companyId: props.companyId,
  };
  programmeCRUD.list(params).then((data) => {
    programmeList.value = data;
  });
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  handleGetProgrammeList();
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = () => {
  emits('requestSuccess');
};
</script>
